#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "identifierTable.h"

identifierTable *createIdentifierTable()
{
  identifierTable *table = (identifierTable *) malloc(sizeof(identifierTable));
  table->head = NULL;
  table->tail = NULL;
  table->counter = 0;

  return table;
}

void deleteIdentifierTable(identifierTable *table)
{
  identifierNode *nextNode = table->head;
  identifierNode *node;

  if (nextNode == NULL) {
    free(table);
    return;
  }

  do {
    node = nextNode;
    nextNode = node->next;
    free(node);
  } while (nextNode != NULL);

  free(table);
}

int addIdentifier(identifierTable *table, const char name[])
{
  identifierNode *node = (identifierNode *) malloc(sizeof(identifierNode));
  strcpy(node->name, name);

  if (table->head == NULL) {
    table->head = node;
  }

  if (table->tail != NULL) {
    table->tail->next = node;
  }

  table->tail = node;

  return table->counter++;
}

char *getIdentifier(identifierTable *table, int index, char *buffer)
{
  identifierNode *node = table->head;
  int i;

  for (i = 0; i < index; i++) {
    if (node == NULL) {
      return NULL;
    }

    node = node->next;
  }

  if (node == NULL) {
    return NULL;
  }

  strcpy(buffer, node->name);
  return buffer;
}

void dumpIdentifierTable(identifierTable *table)
{
  identifierNode *node = table->head;

  while (node != NULL) {
    fprintf(stderr, "%s\n", node->name);
    node = node->next;
  }
}

